package suppliers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import eventservice.EventChannel;
import eventservice.RemotelyPushable;

public class PushSupplier extends TimerTask {

	private final Timer timer;
	private final long interval;
	private RemotelyPushable channelHandle;
	private int counter;

	PushSupplier(RemotelyPushable handle, long interval) {
		timer = new Timer();
		this.interval = interval;
		this.channelHandle = handle;
	}

	public void run() {
		++counter;
		try {
			channelHandle.push(new SimpleEvent(Integer.toString(counter)));
		} catch (RemoteException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public void start() {
		timer.schedule(this, new Date(), interval);
	}

	public void stop() {
		timer.cancel();
	}

	public static void main(String[] args) {
		if (args.length < 3) {
			System.err.println("Usage: PushSupplier host channel_name interval_in_ms");
			return;
		}

		String host = args[0];
		String channelName = args[1];
		long interval = Long.parseLong(args[2]);

		Registry registry = null;
		try {
			registry = LocateRegistry.getRegistry(host);
		} catch (RemoteException e) {
			System.err.println("Cannot locate registry at host '" + host + "': " + e.getMessage());
			return;
		}

		EventChannel channel = null;
		try {
			channel = (EventChannel) registry.lookup(channelName);
		} catch (Exception e) {
			System.err.println("Cannot lookup channel '" + channelName + "': " + e.getMessage());
			return;
		}

		RemotelyPushable handle = null;
		try {
			handle = channel.registerPushSupplier();
		} catch (RemoteException e) {
			System.err.println("Cannot register supplier to channel '" + channelName + "': " + e.getMessage());
			return;
		}

		if (handle == null) {
			System.err.println("Supplier is already registered in '" + channelName + "'.");
			return;
		}

		PushSupplier supplier = new PushSupplier(handle, interval);

		supplier.start();

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					System.in));
			reader.readLine();
		} catch (IOException e) {
		}

		supplier.stop();

		try {
			channel.unregister(handle);
		} catch (RemoteException e) {
			System.err.println(
					"Cannot unregister supplier from channel '" + channelName + "': " + e.getMessage());
		}
	}
}
